package com.aquarium.presentation;

import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import com.aquarium.application.GererMesuresCtrl;
import com.aquarium.application.HelperException;
import com.aquarium.application.NicheAPoissonsException;
import com.aquarium.metier.MesuresDTO;
import com.aquarium.metier.TypeMesure;
import com.aquarium.util.DateUtil;

import eu.schudt.javafx.controls.calendar.DatePicker;

public class EditerMesures implements Initializable {
	
	@FXML private Button b_annuler;
	@FXML private Button b_editer;
	@FXML private DatePicker dp_date_mesure;
	@FXML private ComboBox<String> cb_mesure;
	@FXML private TextField tf_mesure;
	@FXML private HBox hb_date_mesure;
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		new GererMesuresCtrl();
		
		dp_date_mesure = new DatePicker(Locale.FRANCE);
		dp_date_mesure.getStylesheets().add(
				getClass().getResource("ressources/calendarstyle.css")
						.toExternalForm());
		dp_date_mesure.setAlignment(Pos.TOP_CENTER);
		hb_date_mesure.getChildren().add(dp_date_mesure);
		
		
		for(int i=0;i<9;i++){
			cb_mesure.getItems().add(TypeMesure.values()[i]+"");
		}
		
		b_editer.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent arg0) {
				boolean err = true;
				try {
					new GererMesuresCtrl().createObj(
							new MesuresDTO(MesuresDTO.toTypeMesure(cb_mesure.getValue()),
									ListerHistorique.getCb_numaqua().getValue(), 
									DateUtil.toDate(DateUtil.toStr(dp_date_mesure.getSelectedDate())), 
									Double.valueOf(tf_mesure.getText())));
				} catch (NumberFormatException | NicheAPoissonsException
						| HelperException e) {
					new MessageFrame(new Label(e.getMessage()), "Erreur de Saisie", Modality.APPLICATION_MODAL).showAndWait();
					err = false;
				}
				if(err){
					ListerHistorique.updatePanelSimple();
					
					Node  source = (Node)  arg0.getSource();
			    	Stage stage  = (Stage) source.getScene().getWindow();
			    	stage.close();
				}
				
			}
		});
		
		b_annuler.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent arg0) {
				Node  source = (Node)  arg0.getSource();
			    Stage stage  = (Stage) source.getScene().getWindow();
			    stage.close();
				
			}
		});
		
	}

}
